﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using CoolCode.Web; 

namespace CoolCode.Web.UI
{
    /// <summary>
    /// 命名前缀
    /// </summary>
    public enum PrefixType
    {
        /// <summary>
        /// 没有前缀
        /// </summary>
        None,
        /// <summary>
        /// Camel规则（这里是指前缀都是小写）
        /// </summary>
        Camel,
        /// <summary>
        /// 前缀是三个字符
        /// </summary>
        Three,
        /// <summary>
        /// 
        /// </summary>
        UserControl
    }

    public static class PageExtensions
    {    
        //public static IControlManager GetContextManager(this Control container)
        //{
        //    return (container is IControl ? ((IControl)container).ContextManager : null);// new ContextManager(container));
        //}

        #region Model Binder

        //public static void UpdateModel<T>(this Control container, T TModel) where T : class
        //{
        //    UpdateModel<T>(container, TModel, null);
        //    //Controller controller = new Controller();
        //    //controller.ValueProvider = new PrefixableValueProvider(controller.ControllerContext, PrefixType.Camel);
        //    //controller.TryUpdateModel(TModel);
        //}

        //public static void UpdateModel<T>(this Control container, T TModel, string[] includeProperties) where T : class
        //{
        //    Controller controller = new Controller();
        //    controller.ValueProvider = new PrefixableValueProvider(controller.ControllerContext, PrefixType.Camel  );
        //    controller.TryUpdateModel(TModel, includeProperties  );
        //}

        public static void UpdatePage<T>(this  Control container, T TModel) where T : class
        {
            UpdatePage<T>(container , TModel, PrefixType.Camel);
        }

        public static void UpdatePage<T>(this  Control container, T TModel, PrefixType _prefixType) where T : class
        {
            if (TModel == null) return;
            Type type = TModel.GetType();
            var ps = type.GetProperties();// type.GetFastProperties();
            Dictionary<string, object > valueProvider = new Dictionary<string,object >();
            foreach (var p in ps)
            {
                string key = p.Name.ToUpper();
                object value =p.GetValue(TModel, null); // p.Get(TModel);
                valueProvider.Add(key, value); 
            }

            IControlBinder binder = new ControlBinder();
            binder.UpdateControl(container, valueProvider, _prefixType); 
        } 

       #endregion 

    }
}
